import React, { useState } from 'react'
import { Checkbox, Form, Input, Typography, Popconfirm } from 'antd'
import { tableConfig, data, actions } from './config'
import _ from 'lodash'
import CommonTable from '@/common/CommonTable'

const EditableCell = ({
  editing,
  dataindex,
  title,
  children,
  ...restProps
}) => {
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataindex}
          style={{
            margin: 0,
          }}
          rules={[
            {
              required: true,
              message: `Please Input ${title}!`,
            },
          ]}
        >
          <Input />
        </Form.Item>
      ) : (
        children
      )}
    </td>
  )
}
const CheckTable = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const [rowKey] = useState('id')
  const [editingKey, setEditingKey] = useState('')
  const [dataSource, setDataSource] = useState(data)
  const [form] = Form.useForm()

  const isEditing = (record) => record.id === editingKey

  const checkboxChange = (e, id) => {
    const checked = e.target.checked
    const newData = [...selectedRowKeys]
    if (checked) {
      setSelectedRowKeys([...newData, id])
    } else {
      setSelectedRowKeys(_.filter(newData, (o) => o !== id))
    }
  }
  const all = () => {
    setSelectedRowKeys(
      _.map(dataSource, (item, key) => {
        return item.id
      })
    )
  }
  const noAll = () => {
    setSelectedRowKeys([])
  }
  const add = () => {
    form.validateFields().then(() => {
      const id = new Date().getTime()
      form.resetFields()
      setDataSource([...dataSource, { id }])
      setEditingKey(id)
    })
  }
  const actionsClick = {
    all,
    noAll,
    add,
  }
  const mergedColumns = (columns) => {
    return _.map(columns, (item, key) => {
      if (!item.editable) {
        return item
      }

      return {
        ...item,
        onCell: (record, rowIndex) => {
          return {
            record,
            title: item.title,
            dataindex: item.dataIndex,
            editing: isEditing(record),
          }
        },
      }
    })
  }
  const edit = (record) => {
    form.setFieldsValue({
      ...record,
      // eslint-disable-next-line eqeqeq
      gender: record.gender == 0 ? '男' : '女',
    })
    setEditingKey(record.id)
  }
  const cancel = () => {
    setEditingKey('')
  }
  const save = async (record) => {
    const row = await form.validateFields()
    const newData = [...dataSource]
    const index = newData.findIndex((item) => record.id === item.id)
    const item = newData[index]
    newData.splice(index, 1, { ...item, ...row })
    setDataSource(newData)
    setEditingKey('')
  }
  const tableProps = {
    columns: mergedColumns(
      _.map(tableConfig, (item, key) => {
        const obj = { ...item }
        switch (obj.dataIndex) {
          case 'id':
            // eslint-disable-next-line react/display-name
            obj.render = (text, record, index) => {
              const id = record[rowKey]

              return (
                <>
                  <span className="idText">{text}</span>
                  <Checkbox
                    checked={_.filter(selectedRowKeys, (o) => o === id).length}
                    onChange={(e) => checkboxChange(e, id)}
                  />
                </>
              )
            }
            break
          case 'gender':
            // eslint-disable-next-line eqeqeq
            obj.render = (item) => (item == 0 ? '男' : '女')
            break
          case 'action':
            // eslint-disable-next-line react/display-name
            obj.render = (item, record) => {
              const editable = isEditing(record)
              return editable ? (
                <span>
                  <a
                    style={{
                      marginRight: 8,
                    }}
                    onClick={() => save(record)}
                  >
                    Save
                  </a>
                  <Popconfirm title="Sure to cancel?" onConfirm={cancel}>
                    <a>Cancel</a>
                  </Popconfirm>
                </span>
              ) : (
                <Typography.Link
                  disabled={editingKey !== ''}
                  onClick={() => edit(record)}
                >
                  Edit
                </Typography.Link>
              )
            }
            break

          default:
            break
        }
        return obj
      })
    ),
    dataSource,
    rowKey,
    bordered: true,
    actions: _.map(actions, (item, key) => {
      const obj = { ...item }
      obj.onClick = actionsClick[item.id]
      return obj
    }),
    components: {
      body: {
        cell: EditableCell,
      },
    },
  }
  return (
    <Form form={form}>
      <CommonTable {...tableProps} />
    </Form>
  )
}

export default CheckTable
